package com.cly.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.cly.constant.QueueConstant;
import com.cly.model.SmsModel;
import com.cly.service.SmsLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.Channel;

/**
 * 真正发短信的
 */
@Component
@Slf4j
public class SmsListener {

    @Autowired
    private IAcsClient acsClient;

    @Autowired
    private SmsLogService smsLogService;


    /**
     * 流程 member-----mq----->message监听处理
     * 监听短信信息
     * @param message
     * @param channel
     */
    @RabbitListener(queues = QueueConstant.PHONE_SMS_QUEUE, concurrency = "3-5")
    public void smsHandler(Message message, Channel channel){
        //拿到消息
        String msgstr = new String(message.getBody());
        JSONObject jsonObject = JSON.parseObject(msgstr);
        //拿到id
        String userId = jsonObject.getString("userId");
        //拿到消息对象
        SmsModel smsModel = jsonObject.getObject("smsModel", SmsModel.class);
        //真正发短信的方法
        try {
            String resultCode = realSendMsg(smsModel);
            //成功记录数据
            smsLogService.saveSmsLog(userId, resultCode, smsModel);
            //签收
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

        }catch (Exception e){
            log.error("发送短信失败");
        }
    }

    private String realSendMsg(SmsModel smsModel) {
        // 组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        // 使用post提交
        request.setMethod(MethodType.POST);
        // 必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为国际区号+号码，如“85200000000”
        request.setPhoneNumbers(smsModel.getPhoneNumbers());
        // 必填:短信签名-可在短信控制台中找到
        request.setSignName(smsModel.getSignName());
        // 必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
        request.setTemplateCode(smsModel.getTemplateCode());
        request.setTemplateParam(smsModel.getTemplateParam());
        try {
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            System.out.println(sendSmsResponse.getCode());
            return sendSmsResponse.getCode();
        } catch (ClientException e) {
            log.error("发送失败");
        }
        return "发送失败";

    }
}
